package com.hthy.futures.api;


import com.hthy.futures.AppConfig;
import com.hthy.futures.AppContext;
import com.vilyever.socketclient.SocketClient;
import com.vilyever.socketclient.helper.SocketResponsePacket;
import com.vilyever.socketclient.util.CharsetUtil;

import static com.hthy.futures.AppConfig.REMOTEINT;
import static com.hthy.futures.AppConfig.REMOTE_QUOTES_PORT;
import static com.hthy.futures.AppConfig.TEST_REMOTE_PORT4;

/**
   *
   * Author:  Mr.bingley
   * Version:
   * Date:  2017/3/14
   */

public class SocketQuoteManager {
    private SocketClient localSocketClient;


    public SocketClient getLocalSocketClient() {
        if (localSocketClient == null) {
            localSocketClient = new SocketClient();
            setupAddress(localSocketClient);
            setupEncoding(localSocketClient);

            // 存在自动断开的bug
            localSocketClient.getHeartBeatHelper().setHeartBeatInterval(1000 * 5);

            localSocketClient.getHeartBeatHelper().setSendString(AppConfig.HEARTORDER);
        }

        return localSocketClient;
    }

    /* Public Methods */
    public void connect(SocketClient socketClient) {
        socketClient.connect();
    }


    /**
     * 设置远程端地址信息
     */
    private void setupAddress(SocketClient socketClient) {
        socketClient.getAddress().setRemoteIP(AppContext.quoteIp); // 远程端IP地址
        socketClient.getAddress().setRemotePort(AppContext.quotePort); // 远程端端口号
        socketClient.getAddress().setConnectionTimeout(1 * 1000); // 连接超时时长，单位毫秒
    }

    /**
     * 设置自动转换String类型到byte[]类型的编码
     * 如未设置（默认为null），将不能使用{@link SocketClient#sendString(String)}发送消息
     * 如设置为非null（如UTF-8），在接受消息时会自动尝试在接收线程（非主线程）将接收的byte[]数据依照编码转换为String，在{@link SocketResponsePacket#getMessage()}读取
     */
    private void setupEncoding(SocketClient socketClient) {
        socketClient.setCharsetName(CharsetUtil.UTF_8); // 设置编码为UTF-8
    }
}
